#include "sort.h"
#include <string.h>

void sort_bubble_int(int* arr, int n) {
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-1-i; j++)
            if (arr[j] > arr[j+1]) {
                int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
            }
}

void sort_selection_int(int* arr, int n) {
    for (int i = 0; i < n-1; i++) {
        int min_idx = i;
        for (int j = i+1; j < n; j++)
            if (arr[j] < arr[min_idx]) min_idx = j;
        if (min_idx != i) {
            int tmp = arr[i]; arr[i] = arr[min_idx]; arr[min_idx] = tmp;
        }
    }
}

void sort_insertion_int(int* arr, int n) {
    for (int i = 1; i < n; i++) {
        int key = arr[i], j = i-1;
        while (j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = key;
    }
}

void sort_bubble(void* arr, int n, int elem_size, int (*cmp)(const void*, const void*)) {
    char* base = (char*)arr;
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-1-i; j++) {
            char* a = base + j*elem_size;
            char* b = base + (j+1)*elem_size;
            if (cmp(a, b) > 0) {
                char tmp[elem_size];
                memcpy(tmp, a, elem_size);
                memcpy(a, b, elem_size);
                memcpy(b, tmp, elem_size);
            }
        }
    }
} 